<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import debounce from 'lodash/debounce'
import dayjs from 'dayjs'
import { decodeHTML, getUrlSearch } from '../../../utils/token'
import { seachSessionLogPageNew, sessionLogSearch } from '../../../service/api'
const { appContext } = getCurrentInstance()
const proxy = appContext.config.globalProperties
const config = proxy.$config

let localSearchList
try {
  localSearchList = window.localStorage.getItem('localSearchList')
    ? JSON.parse(window.localStorage.getItem('localSearchList'))
    : []
} catch (error) {
  localSearchList = []
}
const list = ref([])
const searchedList = ref(localSearchList) // 搜索记录
const searched = ref(false) // 是否搜索
const loading = ref(false) // 是否加载中
const finished = ref(false) // 是否加载完成
const pageSize = 50 // 每页显示条数
const current = ref(1) // 页码
const getList = () => {
  sessionLogSearch({
    sessionId: config.sessionId,
    current: current.value,
    size: pageSize,
    content: searchVal.value
  })
    .then((res) => {
      proxy.$toast.clear()
      if (current.value === 1) {
        list.value = []
      }
      searched.value = true
      if (res.records.length) {
        res.records.forEach((item) => {
          list.value.push(item)
        })
      }
      if (res.records.length < pageSize) {
        finished.value = true
      } else {
        current.value++
      }
      loading.value = false
    })
    .catch((err) => {
      proxy.$toast(err)
    })
}
// 点击搜索对话列表
const searchVal = ref() // 搜索框的值
const search = () => {
  if (!searchVal.value) return
  loading.value = false
  finished.value = false
  current.value = 1
  if (searchedList.value.indexOf(searchVal.value) < 0) {
    searchedList.value.push(searchVal.value)
    window.localStorage.setItem(
      'localSearchList',
      JSON.stringify(searchedList.value)
    )
  }
  getList()
  proxy.$toast({
    message: '搜索中...',
    duration: 0
  })
}
const clearInput = () => {
  searchVal.value = ''
}
const debounceSearch = debounce(search, 1000)
const cancel = () => {
  console.log(searchVal.value, '取消')
  if (searchVal.value) {
    searchVal.value = ''
    searched.value = false
    loading.value = false
    finished.value = false
    current.value = 1
    list.value = []
  } else {
    // 返回上级路由
    window.history.back()
  }
}

const handleClickHistory = (item) => {
  searchVal.value = item
  search()
}

const addNewDialog = () => {
  window.sessionStorage.setItem('addNewFromSeachPage', '1')
  window.history.back()
}

const handleClickSearchItem = (item) => {
  const { appid, sessionId } = item
  if (appid) {
    window.sessionStorage.setItem('sessionId', sessionId)
    const token = getUrlSearch(window.location.href, 'token')
    const customerServiceConfId = getUrlSearch(
      window.location.href,
      'customerServiceConfId'
    )
    window.location.href = `entity.html?token=${token}&customerServiceConfId=${customerServiceConfId}&id=agent${appid}`
    return
  }
  window.sessionStorage.setItem('clickSearchItemFromSearchPage', '1')
  window.sessionStorage.setItem(
    'clickSearchItemFromSearchPageSession',
    sessionId
  )
  window.history.back()
}

const handleDeleteSearchHistory = () => {
  window.localStorage.removeItem('localSearchList')
  searchedList.value = []
}

onMounted(() => {})
</script>

<template>
  <div class="page-search">
    <div class="input-wrap">
      <div class="input">
        <img @click="search" src="../../../assets/img/search1.png" />
        <input
          type="text"
          placeholder="搜索对话记录"
          v-model="searchVal"
          @input="debounceSearch"
          maxlength="50"
        />
        <img
          v-if="searchVal"
          @click="clearInput"
          src="../../../assets/img/close.png"
        />
      </div>
      <span class="cancel" @click="cancel">取消</span>
    </div>
    <div class="result">
      <template v-if="!searched">
        <div class="search-history">
          <div
            v-if="searchedList.length"
            style="padding-right: 0.4rem; position: relative"
          >
            <i class="delete" @click="handleDeleteSearchHistory" />
            <span
              style="margin-bottom: 0.1rem"
              v-for="(item, index) in searchedList.slice(0, 30)"
              :key="index"
              @click="handleClickHistory(item)"
              >{{ item }}</span
            >
          </div>
          <div class="no-res" v-else>暂无搜索记录</div>
        </div>
      </template>
      <template v-else-if="list.length !== 0">
        <van-list
          class="list"
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="getList"
        >
          <div
            class="item"
            v-for="(item, index) in list"
            :key="index"
            @click="handleClickSearchItem(item)"
          >
            <div class="top">
              <span class="title">{{ item.content || '暂无标题' }}</span>
              <span class="time">{{
                dayjs(item.createTime).format('YYYY/MM/DD')
              }}</span>
            </div>
            <!-- <div class="content oneline">
              {{ item.type === 2 ? config.serviceName : '我' }}：<span>{{
                decodeHTML(item.ask)
              }}</span>
            </div> -->
          </div>
        </van-list>
      </template>
      <template v-else>
        <div class="empty">
          <img src="../../../assets/img/empty.png" />
          <span>没有搜到相关结果</span>
          <div class="addNewDialog" @click="addNewDialog">打开新对话</div>
        </div>
      </template>
    </div>
  </div>
</template>

<style lang="less">
.page-search {
  width: 100%;
  height: 100%;
  background-color: #fff;
  padding: 0 0.32rem;
  font-size: 0.24rem;
  color: #333333;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  .input-wrap {
    display: flex;
    align-items: center;
    margin-top: 0.2rem;
    .input {
      flex: 1;
      font-size: 0.24rem;
      color: #9c9c9b;
      border-radius: 0.24rem;
      padding: 0.2rem 0.32rem;
      background: #eff0f5;
      position: relative;
      display: flex;
      align-items: center;
      img {
        width: 0.3rem;
        height: 0.3rem;
      }
      input {
        flex: 1;
        border: none;
        background: transparent;
        padding-left: 0.1rem;
      }
    }
    .cancel {
      font-size: 0.24rem;
      color: #676767;
      margin-left: 0.2rem;
    }
  }
  .result {
    flex: 1;
    overflow-y: auto;
    margin-top: 0.2rem;
    .empty {
      text-align: center;
      padding-top: 1.76rem;
      color: #b7bfcc;
      font-size: 0.28rem;
      img {
        display: block;
        width: 3.96rem;
        height: 3.96rem;
        margin: 0 auto;
      }
      span {
        display: block;
        margin-top: 0.2rem;
      }
      .addNewDialog {
        width: 1.68rem;
        padding: 0.11rem 0 0.1rem;
        margin: 0.2rem auto;
        text-align: center;
        background: #4792e4;
        border-radius: 0.2rem;
        color: white;
        font-size: 0.24rem;
      }
    }
    .search-history {
      .no-res {
        color: #b7bfcc;
        text-align: center;
      }
      span {
        display: inline-block;
        padding: 0.1rem 0.2rem;
        background: #eff0f5;
        border-radius: 0.24rem;
        margin-right: 0.2rem;
      }
      .delete {
        position: absolute;
        right: 0;
        top: 0;
        width: 0.4rem;
        height: 0.4rem;
        background-image: url('../../../assets/img/delete1.png');
        background-size: 100% 100%;
        margin-right: 0;
      }
    }
    .list {
      .item {
        font-size: 0.24rem;
        color: #666;
        border-top: 0.5px solid #e4ebf4;
        padding: 0.32rem 0;
        .top {
          display: flex;
          justify-content: space-between;
          // margin-bottom: 0.24rem;
          .title {
            color: #444444;
            font-size: 0.26rem;
            font-weight: bold;
          }
          .time {
            color: #78848e;
          }
        }
      }
      .item:first-child {
        border: none;
      }
    }
  }
}
</style>
